<?php
	include_once('../../lib/class.fonctions.php');
	include_once('../../lib/class.db.php');
	include_once('../../lib/class.debug.php');
	include_once('../../lib/class.activerecord.php');
	include_once('../../lib/class.secure.php');
	
	define('BDD_DSN', 'mysql:dbname=cdg;host=localhost'); // DSN BDD
	define('BDD_UTILISATEUR', 'root'); // LOGIN BDD
	define('BDD_MOT_DE_PASSE', ''); // MOT DE PASSE BDD
	
	$gp_fonc = GP_fonctions::getInstance();
	$gp_db = GP_db::getInstance(BDD_DSN, BDD_UTILISATEUR, BDD_MOT_DE_PASSE);
	$gp_request = GP_secure::getInstance();
	
	$table = $gp_request -> Get('table');
	if (strlen($table))
	{
		$fic = '../tables/'.$table.'.xml';
		if (!is_file($fic))
		{
			$requete = "DESCRIBE " . $table;
			$res = $gp_db -> fetchArray($requete);
			$xml = '<champs>';
			foreach ($res as $ligne)
			{
				$xml .= "\n\t<champ>";
				foreach ($ligne as $c => $v)
				{
					if ($c == 'Field')
						$c = 'Name';
					if (!strstr($v, '('))
						$xml .= "\n\t\t<$c>$v</$c>";
					else
					{
						$length = $gp_fonc -> trouver('(', ')', $v);
						$v = str_replace('('.$length.')', '', $v);
						$xml .= "\n\t\t<$c>$v</$c>";
						$xml .= "\n\t\t<Length>$length</Length>";
					}
					if ($c == 'Extra')
					{
						$xml .= "\n\t\t<Display>" . $ligne["Field"] . "</Display>";
						if (strstr(strtolower($ligne["Type"]), 'date'))
							$xml .= "\n\t\t<Input>date</Input>";
						elseif (strstr(strtolower($ligne["Type"]), 'text'))
							$xml .= "\n\t\t<Input>textarea</Input>";
						elseif (strstr(strtolower($ligne["Type"]), 'enum') || strstr(strtolower($ligne["Type"]), 'set'))
						{
							$xml .= "\n\t\t<Input>select</Input>";
							$xml .= "\n\t\t<Vocabulary>" . $ligne["Default"] . "</Vocabulary>";
						}
						elseif (strstr(strtolower($ligne["Type"]), 'blob'))
							$xml .= "\n\t\t<Input>file</Input>";
						else if ($ligne["Key"] == 'MUL')
						{
							$xml .= "\n\t\t<Input>select</Input>";
							$xml .= "\n\t\t<Vocabulary>sql</Vocabulary>";
							$xml .= "\n\t\t<Sql>SELECT FROM ORDER BY ASC</Sql>";
						}
						else
							$xml .= "\n\t\t<Input>text</Input>";
						
						if ($ligne["Key"] == 'PRI')
						{
							$xml .= "\n\t\t<Add>0</Add>";
							$xml .= "\n\t\t<Duplicate>0</Duplicate>";
							$xml .= "\n\t\t<Edit>0</Edit>";
						}
						else
						{
							$xml .= "\n\t\t<Add>1</Add>";
							$xml .= "\n\t\t<Duplicate>1</Duplicate>";
							$xml .= "\n\t\t<Edit>1</Edit>";
						}
						
					}
				}
				$xml .= "\n\t</champ>";
			}
			$xml .= "\n\t<titre></titre>";
			$xml .= "\n</champs>";
			
			
			@touch($fic);
			@chmod($fic, 0777);
			$fp = fopen($fic, 'a');
			fwrite($fp, $xml);
			fclose($fp);
			die('XML généré');
		}
	}
	die('NOK');
	
?>